package com.tender.lc.service;

import com.tender.constants.Constants;
import com.tender.lc.integration.config.properties.MsgProperties;
import com.tender.lc.utils.AddressUtils;
import com.tender.lc.utils.RedisCache;
import com.tender.utils.*;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理 - 工具类
 */
@Component
public class TokenService {
    private static final Logger log = LoggerFactory.getLogger(TokenService.class);

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private MsgProperties  msgProperties;

    /**
     * 获取用户身份信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken();
        if (StringUtils.isNotEmpty(token)) {
            try {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息，该uuid 是用来一起生成 token 的
                String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                // 生成 redis 中的唯一id，根据该key 来获取用户信息
                String userKey = getUserInfoRedisKey(uuid);
                LoginUser user = redisCache.getCacheObject(userKey);
                return user;
            } catch (Exception e) {
                log.error("获取用户信息异常'{}'", e.getMessage());
            }
        }
        return null;
    }

    /**
     * 设置用户身份信息，同时刷新token 过期时间
     */
    public void setLoginUser(LoginUser loginUser) {
        if (null != loginUser && StringUtils.isNotEmpty(loginUser.getUuid())) {
            cacheUserInfo(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String uuid) {
        if (StringUtils.isNotEmpty(uuid)) {
            String userKey = getUserInfoRedisKey(uuid);
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser) {
        String uuid = IdUtils.fastUUID();
        loginUser.setUuid(uuid);
        setUserAgent(loginUser);
        cacheUserInfo(loginUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, uuid);
        // uuid 被用来生成token 返回给前端了
        return createToken(claims);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUser
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            cacheUserInfo(loginUser);
        }
    }

    /**
     * 设置令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void cacheUserInfo(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + msgProperties.getExpireTime());
        // 根据 uuid 将 loginUser 缓存
        String userKey = getUserInfoRedisKey(loginUser.getUuid());
        redisCache.setCacheObject(userKey, loginUser, msgProperties.getExpireTime(), TimeUnit.SECONDS);
    }

    /**
     * 设置用户代理信息
     *
     * @param loginUser 登录信息
     */
    public void setUserAgent(LoginUser loginUser) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr();
        loginUser.setIpaddr(ip);
        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, msgProperties.getSecret()).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(msgProperties.getSecret())
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从令牌中获取用户名
     *
     * 该工具类未使用该方法 TODO
     */
    public String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        // subject 一般是 userId 或者 username
        return claims.getSubject();
    }

    /**
     * 获取请求token
     */
    public String getToken() {
        HttpServletRequest request = ServletUtils.getRequest();
        String token = request.getHeader(msgProperties.getHeader());
        if (StringUtils.isNotBlank(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private String getUserInfoRedisKey(String uuid) {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }

    public LoginUser parse() {
        return parse(getToken());
    }

    public LoginUser parse(String token) {
        Claims claims = parseToken(token);
        String uuid = claims.get(Constants.LOGIN_USER_KEY, String.class);
        return redisCache.getCacheObject(getUserInfoRedisKey(uuid));
    }

}
